<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	private $previous_page = '';
	
	function Login()
	{
		parent::__construct();
		// load language file
		$this->lang->load('i18n');
		$this->load->helper('url');
		
		if (isset($_SERVER['HTTP_REFERER'])){
			$this->previous_page = $_SERVER['HTTP_REFERER'];
		}
		else {
			$this->previous_page = base_url();
		}
	}
	
	public function do_login()
	{
		$user = $_POST['username'];
		$pass = $_POST['password'];
		if(!empty($user) && !empty($pass)) {
			$this->db->where('USERNAME', $user);
			$this->db->where('PASSWORD', $pass);
			$rows = $this->db->get('user');
			foreach ($rows->result() as $user)
			{
				//Destroy old session
				$this->session->sess_destroy();
				//Create a fresh, brand new session
				$this->session->sess_create();
				$this->session->set_userdata("user", $user);
				$this->session->set_userdata("loggedIn", true);
				$this->session->set_userdata("role", $user->ROLE);
				redirect($this->previous_page);
			}
		}
		// Redirect to error page.
		$this->session->set_flashdata("errors", array($this->lang->line('lang.login.error')));
		redirect($this->lang->languageCode().'/login/error', 'location');
	}
	
	public function logout()
	{
		$this->session->sess_destroy();
		redirect($this->lang->languageCode().'/home', 'location');
	}
	
	public function error(){
		$data = array();
		$data['content'] = $this->load->view('error-content.phtml', null, true);
		$this->load->view('mainpage.phtml', $data);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/login.php */